/**
 * 
 */
package cn.miao.learn.ssh.api.filter;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.container.ContainerRequestFilter;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.SecurityContext;

/**
 * @author nealmiao
 *
 */
public class AuthorizationRequestFilter implements ContainerRequestFilter {

	@Context
	HttpServletRequest request;

	@Override
	public void filter(ContainerRequestContext requestContext)
			throws IOException {
		String authHeader = requestContext.getHeaders().getFirst(
				HttpHeaders.AUTHORIZATION);
		System.out.println("authHeader:" + authHeader);
		// 可以模拟/servlet/ApiServlet模拟注入session
		// 可以登录产生时间戳存入数据库（缓存），这里可做对比
		System.out.println(request.getSession().getAttribute("api"));
		final SecurityContext securityContext = requestContext
				.getSecurityContext();
		System.out.println(securityContext.getAuthenticationScheme());

		if (securityContext.isUserInRole("admin")) {
			
		}
		// || (securityContext == null
		// || !securityContext.isUserInRole("privileged"))
		// String authHeader =
		// requestContext.getHeaders().getFirst(HttpHeaders.AUTHORIZATION);
		// if (authHeader != null && authHeader.startsWith("Basic")) {
		// String decoded = new
		// String(Base64.decode(authHeader.substring(6).getBytes()),
		// CHARACTER_SET);

		if (null == request.getSession().getAttribute("api")) {
			requestContext.abortWith(Response
					.status(Response.Status.UNAUTHORIZED)
					.entity("User cannot access the resource.").build());
		}
	}
}